import dayjs from 'dayjs'

/* 生成唯一id, 可指定长度和基数 */
export const uuid = (len: number, charsLen = 62) => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  const radix = charsLen || chars.length
  let i

  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    let r
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  return uuid.join('')
}

/* 全球唯一标识 */
export const guid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

/* 通过当前时间获得唯一id，由时间戳 + uuid构成 */
export const tid = (n = 8) => {
  const time = dayjs().valueOf()
  const radom = uuid(n)
  // 对时间戳进行压缩，减少长度
  return time.toString(36) + radom
}

export default {
  uuid,
  guid,
  tid
}
